/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.model.command;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Interaction;

/**
 * Command to find an interaction with a given name. The command performs a full
 * search through the entire model.
 * 
 * <p>
 * The following attributes must be set for the command to complete
 * successfully:
 * </p>
 * <ul>
 * <li>Name
 * </ul>
 * 
 * <p>
 * The following attributes can be read to access the result of the command:
 * </p>
 * <ul>
 * <li>Interaction - will be null if not found.
 * </ul>
 * 
 * @author frankd@ifi.uio.no
 */
public class FindInteractionCommand extends Command {

	private Element start;
	private String name;
	private Interaction interaction;

	public FindInteractionCommand() {
	}

	public FindInteractionCommand(final Element start, final String name) {
		setStart(start);
		setName(name);
	}

	public void setStart(final Element start) {
		this.start = start;
	}

	public void setName(final String name) {
		this.name = (name != null) ? name.trim() : null;
	}

	public Interaction getInteraction() {
		return interaction;
	}

	@Override
	public void execute() {
		interaction = search(start.getModel());
	}

	private Interaction search(final Element scope) {
		// TODO breadth-first search perhaps better
		if (scope instanceof Interaction) {
			Interaction candidate = (Interaction) scope;
			if (name.equals(candidate.getName()))
				return candidate;
		}

		for (Object o : scope.getOwnedElements()) {
			Interaction i = search((Element) o);
			if (i != null)
				return i;
		}
		return null;
	}

	@Override
	public void undo() {
		interaction = null;
	}

	@Override
	public void redo() {
		this.execute();
	}

	@Override
	public void dispose() {
		start = null;
		name = null;
		interaction = null;
	}
}
